package cn.wgx.springsecuritystudy.config.security;

import cn.wgx.springsecuritystudy.util.ValidateCodeImageUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 获取用户名密码
 *
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    private SessionRegistry sessionRegistry;

    public MyUsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager,SessionRegistry sessionRegistry){
        super();
        this.setAuthenticationManager(authenticationManager);
        this.sessionRegistry = sessionRegistry;
    }

    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        //检测登录验证码
        checkVerifyCode(request, response);
        String username = obtainUsername(request);
        int i = username.hashCode();
        sessionRegistry.registerNewSession(request.getSession(true).getId(), username);
        return super.attemptAuthentication(request, response);
    }




    //检测登录验证码
    public void checkVerifyCode(HttpServletRequest request,
                                   HttpServletResponse response) {
        HttpSession session = request.getSession();
        Object verifyCode = session.getAttribute(ValidateCodeImageUtil.vCodeParameter);
        String vCode = request.getParameter(ValidateCodeImageUtil.vCodeParameter);
        if (verifyCode != null && vCode != null
                && vCode.toUpperCase().equals(verifyCode)) {
        } else {
            throw new AuthenticationServiceException("验证码错误!");
        }
    }

}
